#include <iostream>
#include <cstdlib>
using namespace std;

# 第一次修改
# 第二次修改

void snake(int **arr, int m, int n)
{
    for (int i = 0; i < m; i++)
    {
        if ((i+1)%2==1)
        {
            for (int j = 0; j < n; j++)
                cout<<((i==0&&j==0)?"":" ")<<arr[i][j];
        }
        else
        {
            for (int j = n-1; j >= 0; j--)
                cout<<" "<<arr[i][j];
        }
    }
}

void roll(int **arr, int m, int n)
{
    int x = 0, y = 0, direction = 0;
    int min_x = 0, min_y = 0, max_x = m, max_y = n;
    int num = m * n;
    while (num --)
    {
        cout<<((x==0&&y==0)?"":" ")<<arr[x][y];
        switch (direction)
        {
            case 0:
                y++;
                if (y == max_y)
                {
                    x ++;
                    y --;
                    max_y --;
                    direction = (direction + 1) % 4;
                }
                break;
            case 1:
                x++;
                if (x == max_x)
                {
                    y --;
                    x --;
                    max_x --;
                    direction = (direction + 1) % 4;
                }
                break;
            case 2:
                y--;
                if (y < min_y)
                {
                    x --;
                    y ++;
                    min_y ++;
                    direction = (direction + 1) % 4;
                }
                break;
            case 3:
                x--;
                if (x == min_x)
                {
                    y ++;
                    x ++;
                    min_x ++;
                    direction = (direction + 1) % 4;
                }
                break;
        }
    }
}

int main()
{
    int m, n;
    cin>>m>>n;
    int **arr = (int **)malloc(sizeof(int*)*m);
    for (int i = 0; i < m; i++)
        arr[i] = (int *)malloc(sizeof(int)*n);
    for (int i = 0; i < m; i++)
        for (int j = 0; j < n; j++)
            cin>>arr[i][j];
    snake(arr, m, n); cout<<endl;
    roll(arr, m, n);
    return 0;
}
